package com.wenlin.image.service.impl;

import com.wenlin.image.response.ImageDTO;
import com.wenlin.image.response.Message;
import com.wenlin.image.service.ImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;

/***
 *  Created with IntelliJ IDEA.
 *  User:  wenlin
 *  Date:  2017/12/6
 *  Time:  14:49
 *  Description:
 **/
@Service
public class ImageServiceImpl implements ImageService{
    private static Logger logger = LoggerFactory.getLogger(ImageServiceImpl.class);

    @Override
    public Message process(String userId, MultipartFile pictureFile) {
        Message message = new Message();
        String avatarUri = "";
        try {
            avatarUri = uploadPicture(pictureFile, userId);
            logger.info("用户ID为：" + userId + "上传图片成功");
            ImageDTO imageDTO = new ImageDTO();
            imageDTO.setImageUrl(avatarUri);
            imageDTO.setHost(getHost());
            message.setData(imageDTO);
        } catch (IllegalStateException | IOException e) {
            logger.warn("用户ID为：" + userId + "上传图片失败");
            message.setCode(201014);
            message.setMsg("上传图片失败");
            return message;
        }
        return  message;
    }




    /**
     * 上传图片
     *
     * @param pictureFile 图片资源
     * @param userDir     用户路径
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    private String uploadPicture(MultipartFile pictureFile, String userDir) throws IllegalStateException, IOException {
        // 原始文件名称
        String pictureFile_name = pictureFile.getOriginalFilename();

        long currentTime = System.currentTimeMillis();

        // 新文件名称
        StringBuilder newFileName = new StringBuilder();
        newFileName.append(currentTime);
        newFileName.append(pictureFile_name.substring(pictureFile_name.lastIndexOf(".")));

        createDir("/data/wwwroot/default/images/user/" + userDir);

        // 向磁盘写文件
        try {

            Files.copy(pictureFile.getInputStream(), Paths.get("/data/wwwroot/default/images/user/" + userDir + "/" + newFileName));

        } catch (Exception e) {
            e.printStackTrace();
        }

        StringBuilder avatarUri = new StringBuilder();
        avatarUri.append("user/");
        avatarUri.append(userDir);
        avatarUri.append("/");
        avatarUri.append(newFileName);

        return avatarUri.toString();
    }

    // 创建目录
    private static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            System.out.println("创建目录失败，目标目录已存在！");
            return true;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            return true;
        } else {
            return false;
        }
    }
     /***
      *  User:  wenlin
      *  Date:  2017/12/6
      *  Time:  15:35
      *  Description:获取本机ip地址
      **/
     private String getHost(){
         String host = null;
         try {
             host = InetAddress.getLocalHost().getHostAddress();
         } catch (UnknownHostException e) {
             logger.error("get server host Exception e:", e);
         }
         return  host;
     }
}
